<html>
<head>
<script src="../resources/js-test.js"></script>
<script src="../resources/user-gesture-utils.js"></script>
<script src="vibration-utils.js"></script>
</head>
<body>
<h4 id="test"></h4>
<script>
description('Tests the cancelVibration during pattern vibration is working.');

// Simulates a user click for vibrate to be allowed.
var element = document.getElementById("test");
simulateUserClick(element.offsetLeft + 2, element.offsetTop + 2);

function vibrate(pattern) {
    navigator.vibrate(pattern);
    shouldBeTrue('internals.isVibrating(navigator)');
}

function cancelVibration(time) {
    setTimeout(function() {
        navigator.vibrate(0);
        shouldBeFalse('internals.isVibrating(navigator)');
        doNextTest();
    }, time);
}

function doNextTest() {
    if (count == 4)
        finishJSTest();
    doTest(++count);
}

function doTest(num) {
    switch(num) {
    case 1: // Test that cancelling works during a vibration in a pattern.
        vibrate([20, 20, 20]);
        // Progress time by 10ms so we are in the middle of the first vibration of the pattern.
        cancelVibration(10);
        break;
    case 2: // Test that cancelling works during a pause in a pattern.
        vibrate([10, 10, 10]);
        // Progress time by 15ms so we are in the middle of the first pause of the pattern.
        cancelVibration(15);
        break;
    case 3: // Test that the system stops thinking that it is vibrating when the pattern ends.
        vibrate([10, 10, 10]);
        // Progress time by 35ms so the pattern ends naturally without interruptions.
        cancelVibration(35);
        break;
    case 4: // Test that a trailing pause is stripped so isVibrating becomes false after the last vibration in the pattern.
        vibrate([10, 10, 10, 10]); // Even number of array entries, the trailing pause will be stripped.
        // Progress time by 35ms so the pattern ends naturally without interruptions.
        cancelVibration(35);
        break;
    }
}

var count = 1;
if (window.testRunner) {
    window.jsTestIsAsync = true;
    shouldBeFalse('internals.isVibrating(navigator)'); // Before vibration test.
    doTest(count);
} else {
    debug('This test can not be run without the TestRunner');
}
</script>
</body>
</html>
